package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.VocabularyInfo
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.viewmodel.UserInfoViewModel
import kotlinx.android.synthetic.main.fragment_words_cognition.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException

/**
 * @author : Admin
 * @date   : 2020/11/27
 * @desc   :
 */
class WordsCognitionFragment : BaseFragment(), OnChartValueSelectedListener {
    private val pieEntries = mutableListOf<PieEntry>()
    private val colors = mutableListOf<Int>()
    private val zsdArea by lazy { arguments?.getString("zsdarea") }
    private lateinit var viewModel: PaperViewModel
    override fun createLayout(): Int {
        return R.layout.fragment_words_cognition
    }

    override fun initView(view: View?) {
        viewModel = ViewModelProvider(requireActivity()).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        button.setOnClickListener {
            startActivity(Intent(requireContext(), VocabTrailActivity::class.java).apply {
                putExtra("zsd", zsdArea)
                putExtra("stuID", viewModel.StuID.value)
            })
        }
        getStuVocabulary()
    }

    @SuppressLint("CheckResult", "StringFormatInvalid")
    private fun getStuVocabulary() {
        val method = BkApiMethods(requireContext())
        val params = BkApiMethods.Paramas()
        params["ZsdArea"] = zsdArea
        params["StuID"] = viewModel.StuID.value
        method.getStuVocabulary(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                if (it.Data.TotalWord == 0) {
                    group.visibility = View.GONE
                    tv_empty.visibility = View.VISIBLE
                } else {
                    group.visibility = View.VISIBLE
                    tv_empty.visibility = View.GONE
                    initVocabInfo(it.Data)
                    initPieChart(it.Data)
                }
            } else {
                MyToast.showToast( it.Message)
            }
        }, {
            val error: String = if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                getString(R.string.aibk_network_timeout)
            } else {
                getString(R.string.aibk_server_sick)
            }
            MyToast.showToast(error)
        })
    }

    @SuppressLint("SetTextI18n")
    private fun initVocabInfo(data: VocabularyInfo) {
        when (data.Conclusion) {
            0 -> {
                tv_extra.visibility = View.GONE
                tv_percent.visibility = View.GONE
                iv_icon.setImageResource(R.mipmap.aibk_icon_vocab_no)
                tv_vocabinfo_child.visibility = View.GONE
                tv_vocabinfo_sub.visibility = View.GONE
                val graspWord = data.TotalGraspWord.toString()
                val unGraspWord = data.TotalUnGraspWord.toString()
                val unAssessWord = data.TotalUnAssessWord.toString()
                tv_vocabinfo.visibility = View.VISIBLE
                tv_vocabinfo.text = HtmlUtils.setText(
                    "熟练掌握词汇${graspWord}个，薄弱词汇${unGraspWord}个；（尚有${unAssessWord}个词汇未采集到学习数据）")
                val strInfo = tv_vocabinfo.text
                val indexGraspWord = strInfo.indexOf(graspWord)
                val spanStr = SpannableString(strInfo)
                addClickSpan(spanStr, "#22d7bb", indexGraspWord, indexGraspWord + graspWord.length,
                        0, data.TotalGraspWord)
                addClickSpan(
                        spanStr, "#ffd234", indexGraspWord + graspWord.length + 6,
                        indexGraspWord + graspWord.length + 6 + unGraspWord.length, 1, data.TotalUnGraspWord
                )
                addClickSpan(spanStr, "#e1e1e1",
                    indexGraspWord + graspWord.length + 11 + unGraspWord.length,
                    indexGraspWord + graspWord.length + 11 + unGraspWord.length + unAssessWord
                        .length,
                        2,
                        data.TotalUnAssessWord
                )
                tv_vocabinfo.text = spanStr
                tv_vocabinfo.movementMethod = LinkMovementMethod.getInstance()
            }
            else -> {
                tv_extra.visibility = View.VISIBLE
                tv_percent.visibility = View.VISIBLE
                tv_extra.text ="${Ext.TESTNAME}必考词汇掌握率"
                tv_percent.text = HtmlUtils.setText(getString(R.string.words_percent,
                    BigDecimal(data.MasterRate * 100).setScale(1, BigDecimal.ROUND_HALF_UP)
                        .stripTrailingZeros().toPlainString()))
                when (data.Conclusion) {
                    1 -> {
                        iv_icon.setImageResource(R.mipmap.aibk_icon_vocab_c)
                        tv_vocabinfo_child.visibility = View.VISIBLE
                        tv_vocabinfo_child.text = "词汇量小"
                        tv_vocabinfo_child.setTextColor(Color.parseColor("#ffd234"))
                        tv_vocabinfo_sub.visibility = View.VISIBLE
                        tv_vocabinfo_sub.text = HtmlUtils.setText("<font color='#ffd234'>${
                            BigDecimal(
                                data.TotalUnGraspWord.toDouble() * 100 / data.TotalWord.toDouble()).setScale(
                                1, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString()
                        }%</font>${Ext.TESTNAME}必考词汇未掌握，<font color='#e1e1e1'>${
                            BigDecimal(100) - BigDecimal(
                                data.TotalUnGraspWord.toDouble() * 100 / data.TotalWord.toDouble()).setScale(
                                1, BigDecimal.ROUND_HALF_UP) - BigDecimal(
                                data.MasterRate * 100).setScale(1, BigDecimal.ROUND_HALF_UP)
                        }%</font>${Ext.TESTNAME}必考词汇未学习噢~")
                        tv_vocabinfo.visibility = View.GONE
                    }
                    2 -> {
                        iv_icon.setImageResource(R.mipmap.aibk_icon_vocab_b)
                        tv_vocabinfo_child.visibility = View.VISIBLE
                        tv_vocabinfo_child.text = "词汇量一般"
                        tv_vocabinfo_child.setTextColor(Color.parseColor("#22d7bb"))
                        tv_vocabinfo_sub.visibility = View.VISIBLE
                        tv_vocabinfo_sub.text = HtmlUtils.setText("<font color='#22d7bb'>${
                            BigDecimal(
                                data.TotalUnGraspWord.toDouble() * 100 / data.TotalWord.toDouble()).setScale(
                                1, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString()
                        }%</font>${Ext.TESTNAME}必考词汇未掌握，<font color='#e1e1e1'>${
                            BigDecimal(100) - BigDecimal(
                                data.TotalUnGraspWord.toDouble() * 100 / data.TotalWord.toDouble()).setScale(
                                1, BigDecimal.ROUND_HALF_UP) - BigDecimal(
                                data.MasterRate * 100).setScale(1, BigDecimal.ROUND_HALF_UP)
                        }%</font>${Ext.TESTNAME}必考词汇未学习噢~")
                        tv_vocabinfo.visibility = View.GONE
                    }
                    3 -> {
                        iv_icon.setImageResource(R.mipmap.aibk_icon_vocab_a)
                        tv_vocabinfo_child.visibility = View.VISIBLE
                        tv_vocabinfo_child.text = "词汇量较大"
                        tv_vocabinfo_child.setTextColor(Color.parseColor("#2dbcff"))
                        tv_vocabinfo_sub.visibility = View.VISIBLE
                        tv_vocabinfo_sub.text = HtmlUtils.setText("<font color='#2dbcff'>${
                            BigDecimal( data.MasterRate * 100).setScale(1,
                                BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString()
                        }%</font>${Ext.TESTNAME}必考词汇已掌握了噢~")
                        tv_vocabinfo.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun addClickSpan(str: SpannableString, color: String, start: Int, end: Int, type: Int, num: Int) {
        str.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                if (num == 0) {
                    return
                }
                val intent = Intent().apply {
                    putExtra("type", type)
                    putExtra("zsd", zsdArea)
                    putExtra("stuID", viewModel.StuID.value)
                }
                if (type != 2) {
                    intent.setClass(requireContext(), VocabListActivity::class.java)
                } else {
                    intent.setClass(requireContext(), UnStudyVocabListActivity::class.java)
                }
                startActivity(intent)
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = Color.parseColor(color)
                ds.isUnderlineText = true
            }
        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }

    private fun initPieChart(data: VocabularyInfo) {
        if (data.Conclusion == 0) {
            pieEntries.clear()
            val dataMap = mapOf("熟练掌握" to data.TotalGraspWord.toFloat(),
                "薄弱" to data.TotalUnGraspWord.toFloat(), "尚未学习" to data.TotalUnAssessWord.toFloat())
            val sortedMap = dataMap.toList().sortedByDescending { it.second }
            pieEntries.add(PieEntry(sortedMap[1].second, sortedMap[1].first))
            colors.clear()
            colors.add(Color.parseColor(when (sortedMap[1].first) {
                "熟练掌握" -> "#22d7bb"
                "薄弱" -> "#ffd234"
                else -> "#e1e1e1"
            }))
            pieEntries.add(PieEntry(sortedMap[0].second, sortedMap[0].first))
            colors.add(Color.parseColor(when (sortedMap[0].first) {
                "熟练掌握" -> "#22d7bb"
                "薄弱" -> "#ffd234"
                else -> "#e1e1e1"
            }))
            pieEntries.add(PieEntry(sortedMap[2].second, sortedMap[2].first))
            colors.add(Color.parseColor(when (sortedMap[2].first) {
                "熟练掌握" -> "#22d7bb"
                "薄弱" -> "#ffd234"
                else -> "#e1e1e1"
            }))
            val percent = BigDecimal(100) - BigDecimal(
                data.TotalGraspWord.toDouble() * 100 / data.TotalWord.toDouble()).setScale(0,
                RoundingMode.HALF_UP) - BigDecimal(
                data.TotalUnGraspWord.toDouble() * 100 / data.TotalWord.toDouble()).setScale(0,
                RoundingMode.HALF_UP)
            val pieManager = PieChartManager(chart_words_cognition, "words",
                percent.intValueExact())
            pieManager.showSolidPieChart(pieEntries, colors)
        } else {
            pieEntries.clear()
            val dataMap = mapOf("听说" to data.LSGraspWord.toFloat(),
                "阅读" to data.RWGraspWord.toFloat(), "尚未学习" to data.TotalUnAssessWord.toFloat(),
                "总" to data.TotalWord.toFloat() - data.LSGraspWord.toFloat() - data.RWGraspWord.toFloat())
            val sortedMap = dataMap.toList().sortedByDescending { it.second }
            pieEntries.add(PieEntry(data.RWGraspWord.toFloat(), "阅读词汇总量" + data.RWWord + "个"))
            colors.clear()
            colors.add(Color.parseColor("#ffd234"))
            pieEntries.add(PieEntry(data.TotalUnAssessWord.toFloat(),
                "尚未学习总词汇量" + data.TotalUnAssessWord + "个"))
            colors.add(Color.parseColor("#e1e1e1"))
            pieEntries.add(PieEntry(
                data.TotalWord.toFloat() - data.LSGraspWord.toFloat() - data.RWGraspWord.toFloat(),
                "总词汇量" + data.TotalWord + "个"))
            colors.add(Color.parseColor("#2dbcff"))
            pieEntries.add(PieEntry(data.LSGraspWord.toFloat(), "听说词汇总量" + data.LSWord + "个"))
            colors.add(Color.parseColor("#22d7bb"))
            val pieManager = PieChartManager(chart_words_cognition, "words", 0)
            pieManager.showRingPieChart(pieEntries, colors)
        }
        chart_words_cognition.setOnChartValueSelectedListener(this)
    }

    private fun getNum(str: String, data: VocabularyInfo): String {
        return when {
            str.contains("听说") -> {
                "听说词汇总量" + data.LSWord + "个"
            }
            str.contains("阅读") -> {
                "阅读词汇总量" + data.RWWord + "个"
            }
            else -> {
                "总词汇量" + data.TotalWord + "个"
            }
        }
    }

    override fun onValueSelected(e: Entry?, h: Highlight?) {
        e ?: return
        val label = (e as PieEntry).label
        val intent = Intent().apply {
            putExtra("zsd", zsdArea)
        }
        when {
            label == "熟练掌握" -> {
                intent.setClass(requireContext(), VocabListActivity::class.java)
                intent.putExtra("type", 0)
            }
            label == "薄弱" -> {
                intent.setClass(requireContext(), VocabListActivity::class.java)
                intent.putExtra("type", 1)
            }
            label.contains("听说") -> {
                intent.setClass(requireContext(), VocabListActivity::class.java)
                intent.putExtra("type", 2)
            }
            label.contains("阅读") -> {
                intent.setClass(requireContext(), VocabListActivity::class.java)
                intent.putExtra("type", 3)
            }
            label.contains("尚未学习") -> {
                intent.setClass(requireContext(), UnStudyVocabListActivity::class.java)
            }
            label.contains("总词汇量") -> {
                intent.setClass(requireContext(), VocabListActivity::class.java)
                intent.putExtra("type", -1)
            }
        }
        intent.putExtra("stuID", viewModel.StuID.value)
        startActivity(intent)
    }

    override fun onNothingSelected() {

    }
}